package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.QuestionItem;
import com.itheima.utils.BeanUtil;
import com.itheima.web.BaseServlet.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/store/questionItem")
public class QuestionItemServlet extends BaseServlet {
    /**
     * 分页查询
     *
     * @param request
     * @param response
     * @return
     */
    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String questionId = request.getParameter("questionId");
        PageInfo<QuestionItem> info = questionItemService.findAll(questionId);
        request.setAttribute("page", info);
        //进入list页时,添加对应的问题id,为添加操作使用
        request.setAttribute("questionId", questionId);
        request.getRequestDispatcher("/WEB-INF/pages/store/questionItem/list.jsp").forward(request, response);
    }

    public void saveOrUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        QuestionItem questionItem = BeanUtil.fillBean(request, QuestionItem.class, "yyyy-MM-dd");
        if (StringUtils.isNotBlank(questionItem.getId())){
            questionItemService.update(questionItem);
        }else {
            questionItemService.save(questionItem);
        }
        list(request,response);
    }

    /**
     * 跳转到修改界面,并回显数据
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        QuestionItem questionItem = questionItemService.findById(id);
        request.setAttribute("questionItem", questionItem);
        list(request, response);
    }


    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String id = request.getParameter("id");
        questionItemService.delete(id);
        //跳转回到list界面
        list(request, response);
    }
}
